var ctx;

function setCtx(ctx) {
    this.ctx = ctx;
}

$(function() {
    initListener1(); // 添加区域监听事件1
    initListener2(); // 添加区域监听事件2
})

/* 返回给商户入驻--营业执照--省市区级联 */
function initListener1() {
    $("#province1").change(
            function() {
                province = $('#province1').val();
                if (province != '') {
                    $.ajax({
                        type : "GET",
                        url : ctx + "/district/getDistrictInfoByParentId",
                        cache : false,
                        dataType : 'json',
                        data : {
                            parentId : province
                        },
                        success : function(data) {
                            if (data.success) {
                                var result = "<option value='"
                                        + "'>--城市--</option>";
                                $.each(data.obj, function(index, item) {
                                    result += "<option id='" + item.regionName
                                            + "'" + " value='" + item.id + "'>"
                                            + item.regionName + "</option>";
                                });
                                $("#city1").html('');
                                $("#city1").append(result);
                                $("#city1").change();
                            }
                        }
                    });
                } else {
                    var result = "<option value='" + "'>--城市--</option>";
                    $("#city1").html('');
                    $("#city1").append(result);
                    $("#city1").change();
                }
            });

    $("#city1").change(
            function() {
                city = $('#city1').val();
                if (city != '') {
                    $.ajax({
                        type : "GET",
                        url : ctx + "/district/getDistrictInfoByParentId",
                        cache : false,
                        dataType : 'json',
                        data : {
                            parentId : city
                        },
                        success : function(data) {
                            if (data.success) {
                                var result = "<option value='"
                                        + "'>--区--</option>";
                                $.each(data.obj, function(index, item) {
                                    result += "<option id='" + item.regionName
                                            + "'" + " value='" + item.id + "'>"
                                            + item.regionName + "</option>";
                                });
                                $("#district1").html('');
                                $("#district1").append(result);
                                $("#district1").change();
                            }
                        }
                    });
                } else {
                    var result = "<option value='" + "'>--区--</option>";
                    $("#district1").html('');
                    $("#district1").append(result);
                    $("#district1").change();
                }
            });
}

/* 返回给商户入驻--公司地址--省市区级联 */
function initListener2() {
    $("#province2").change(
            function() {
                province = $('#province2').val();
                if (province != '') {
                    $.ajax({
                        type : "GET",
                        url : ctx + "/district/getDistrictInfoByParentId",
                        cache : false,
                        dataType : 'json',
                        data : {
                            parentId : province
                        },
                        success : function(data) {
                            if (data.success) {
                                var result = "<option value='"
                                        + "'>--城市--</option>";
                                $.each(data.obj, function(index, item) {
                                    result += "<option id='" + item.regionName
                                            + "'" + " value='" + item.id + "'>"
                                            + item.regionName + "</option>";
                                });
                                $("#city2").html('');
                                $("#city2").append(result);
                                $("#city2").change();
                            }
                        }
                    });
                } else {
                    var result = "<option value='" + "'>--城市--</option>";
                    $("#city2").html('');
                    $("#city2").append(result);
                    $("#city2").change();
                }
            });

    $("#city2").change(
            function() {
                city = $('#city2').val();
                if (city != '') {
                    $.ajax({
                        type : "GET",
                        url : ctx + "/district/getDistrictInfoByParentId",
                        cache : false,
                        dataType : 'json',
                        data : {
                            parentId : city
                        },
                        success : function(data) {
                            if (data.success) {
                                var result = "<option value='"
                                        + "'>--区--</option>";
                                $.each(data.obj, function(index, item) {
                                    result += "<option id='" + item.regionName
                                            + "'" + " value='" + item.id + "'>"
                                            + item.regionName + "</option>";
                                });
                                $("#district2").html('');
                                $("#district2").append(result);
                                $("#district2").change();
                            }
                        }
                    });
                } else {
                    var result = "<option value='" + "'>--区--</option>";
                    $("#district2").html('');
                    $("#district2").append(result);
                    $("#district2").change();
                }
            });
}

// 验证公司名称不为空
function checkShopName() {
    var shopName = $("#shopName").val();
    if (shopName == $("#shopName").attr("placeholder")) {
        shopName = "";
    }
    if (shopName == null || shopName == "") {
        layer.tips('请填写店铺名称!', '#shopName', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证公司名称不为空
function checkCompanyName() {
    var companyName = $("#companyName").val();
    if (companyName == $("#companyName").attr("placeholder")) {
        companyName = "";
    }
    if (companyName == null || companyName == "") {
        layer.tips('请填写公司名称!', '#companyName', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}
// 验证营业执照注册号不为空
function checkBusinessLicense() {
    var businessLicense = $("#businessLicense").val();
    var reg = /^\d{15}$/;
    
    if (businessLicense == $("#businessLicense").attr("placeholder")) {
        businessLicense = "";
    }
    if (businessLicense == null || businessLicense == "") {
        layer.tips('请填写营业执照注册号!', '#businessLicense', {
            tips : 3,
            time : 1000
        });
        return false;
    } else if (reg.test(businessLicense)) {
        return true;
    } else {
        layer.tips('请填写15位营业执照注册号!', '#businessLicense', {
            tips : 3,
            time : 1000
        });
        return false;

    }
}

// 验证注册资本不能为空
function checkMoney() {
    var registerMoney = $("#registerMoney").val();
    var reg = new RegExp("^[0-9]*$");

    if (registerMoney == null || registerMoney == ""
            || (!reg.test(registerMoney))) {
        layer.tips('请填写注册资本!', '#registerMoney', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证法定代表人姓名不为空
function checkLegalName() {
    var legalName = $("#legalName").val();
    if (legalName == $("#legalName").attr("placeholder")) {
        legalName = "";
    }
    if (legalName == null || legalName == "") {
        layer.tips('请填写法定代表人姓名!', '#legalName', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}
// 验证身份证号不为空且格式正确:
// 1、15位或18位，如果是15位，必需全是数字。
// 2、如果是18位，最后一位可以是数字或字母Xx，其余必需是数字。
function checkLegalIdcard() {
    var legalIdcard = $("#legalIdcard").val();
    if (legalIdcard == $("#legalIdcard").attr("placeholder")) {
        legalIdcard = "";
    }
    if (legalIdcard == null || legalIdcard == "") {
        layer.tips('请填写身份证号!', '#legalIdcard', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        var reg = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/;
        if (!reg.test(legalIdcard)) {
            layer.tips('身份证号格式错误，请重新填写！', '#legalIdcard', {
                tips : 3,
                time : 1000
            });
            return false;
        } else {
            return true;
        }
    }
    /*
     * var reg=new RegExp("^[0-9]*$");
     * 
     * if ((CardNo == "")||(!(!reg.test(CardNo))&&(CardNo.length ==
     * 15))||(!(reg.test(CardNo.substr(0,17)))&&(CardNo.length ==
     * 18))||((CardNo.length != 15)&&(CardNo.length != 18))) {
     * layer.tips('您的身份证号码输入有误，必需是15数字或18位,请重新检查并输入!', '#legalIdcard', { tips:
     * 3, time:1000 }); return false; } else if (CardNo.length == 15) {
     * if(CardNo.substr(8,2)>12||CardNo.substr(8,2)<1) {
     * layer.tips('您身份证的出生“月”输入有误,请重新检查并输入!', '#legalIdcard', { tips: 3,
     * time:1000 }); return false; }
     * if(CardNo.substr(10,2)>31||CardNo.substr(10,2)<1) {
     * layer.tips('您身份证的出生“日”输入有误,请重新检查并输入!', '#legalIdcard', { tips: 3,
     * time:1000 }); return false; } } else if (CardNo.length == 18) {
     * 
     * if(CardNo.substr(6,4)<1900||CardNo.substr(6,4)>2100) {
     * layer.tips('您身份证的出生“年”输入有误,请重新检查并输入!', '#legalIdcard', { tips: 3,
     * time:1000 }); return false; }
     * if(CardNo.substr(10,2)>12||CardNo.substr(10,2)<1) {
     * layer.tips('您身份证的出生“月”输入有误,请重新检查并输入!', '#legalIdcard', { tips: 3,
     * time:1000 }); return false; }
     * if(CardNo.substr(12,2)>31||CardNo.substr(12,2)<1) {
     * layer.tips('您身份证的出生“日”输入有误,请重新检查并输入!', '#legalIdcard', { tips: 3,
     * time:1000 }); return false; } }
     * 
     * var Wi = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2); var Ai = new
     * Array('1','0','X','9','8','7','6','5','4','3','2');
     * 
     * if (CardNo.charAt(17) == 'x') { CardNo = CardNo.replace("x","X"); }
     * 
     * var checkDigit = CardNo.charAt(17); var cardNoSum = 0;
     * 
     * for (var i=0; i<CardNo.length-1; i++) { cardNoSum = cardNoSum +
     * CardNo.charAt(i)*Wi[i]; }
     * 
     * var seq = cardNoSum%11; var getCheckDigit = Ai[seq];
     * 
     * if (checkDigit != getCheckDigit) { layer.tips('您的身份证号码校验失败，请重新检查并输入!',
     * '#legalIdcard', { tips: 3, time:1000 }); return false; } else { return
     * true; }
     */

}
// 验证法人身份证电子版不为空
function checkImageLogo() {
    var imageLogo = $("#imageLogo").val();
    if (imageLogo == $("#imageLogo").attr("placeholder")) {
        imageLogo = "";
    }
    if (imageLogo == null || imageLogo == "") {
        layer.tips('请上传法人身份证电子版!', '#imageLogo', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}
// 验证省不能为空
function checkProvinceName1() {
    var province = $("#province1").val();
    if (province == null || province == "") {
        layer.tips('请选择省!', '#province1', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证市名称不能为空
function checkCityName1() {
    /*
     * var province = $("#province1").val(); if(province == null || province ==
     * ""){ layer.tips('请先选择省!', '#city1', { tips: 3, time:1000 }); return
     * false; }else{ return true; }
     */
    var city = $("#city1").val();
    if (city == null || city == "") {
        layer.tips('请选择市!', '#city1', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证区名称不能为空
function checkDistrict1() {
    /*
     * var city = $("#city1").val(); if(city == null || city == ""){
     * layer.tips('请先选择市!', '#district1', { tips: 3, time:1000 }); return false;
     * }else{ return true; }
     */

    var district1 = $("#district1").val();
    if (district1 == null || district1 == "") {
        layer.tips('请选择区!', '#district1', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证公司所在地省不能为空
function checkProvinceName2() {
    var province2 = $("#province2").val();
    if (province2 == null || province2 == "") {
        layer.tips('请选择省!', '#province2', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证公司所在地市名称不能为空
function checkCityName2() {
    var city2 = $("#city2").val();
    if (city2 == null || city2 == "") {
        layer.tips('请选择市!', '#city2', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证公司所在地区名称不能为空
function checkDistrict2() {

    var district2 = $("#district2").val();
    if (district2 == null || district2 == "") {
        layer.tips('请选择区!', '#district2', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 验证营业执照详细地址不为空
function checkBusinessLicenseAddress() {
    var businessLicenseAddress = $("#businessLicenseAddress").val();
    if (businessLicenseAddress == $("#businessLicenseAddress").attr(
            "placeholder")) {
        businessLicenseAddress = "";
    }
    if (businessLicenseAddress == null || businessLicenseAddress == "") {
        layer.tips('请填写营业执照详细地址!', '#businessLicenseAddress', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}
// 验证成立日期不为空
function checkRegisterDate() {
    var registerDate = $("#registerDate").val();
    if (registerDate == $("#registerDate").attr("placeholder")) {
        registerDate = "";
    }
    if (registerDate == null || registerDate == "") {
        layer.tips('请填写成立日期!', '#registerDate', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}
// 验证开始营业期限不为空
function checkBeginDate() {
    var beginDate = $("#beginDate").val();
    if (beginDate == $("#beginDate").attr("placeholder")) {
        beginDate = "";
    }
    if (beginDate == null || beginDate == "") {
        layer.tips('请填写开始营业期限!', '#beginDate', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}
// 验证结束营业期限不为空
function checkEndDate() {
    var endDate = $("#endDate").val();
    var check = document.getElementById('check').checked; // 这里返回 true 或 false
    if (endDate == $("#endDate").attr("placeholder")) {
        endDate = "2060-01-01";
    }
    if (check) {
        return true;
    } else {
        if (endDate == null || endDate == "") {
            layer.tips('请填写结束营业期限!', '#endDate', {
                tips : 3,
                time : 1000
            });
            return false;
        } else {
            return true;
        }

    }
}

// 验证公司联系电话
function checkCompanyPhone() {
    var companyPhone = $("#companyPhone").val();
    if (companyPhone == $("#companyPhone").attr("placeholder")) {
        companyPhone = "";
    }
    if (companyPhone == null || companyPhone == "") {
        layer.tips('请填写公司联系电话!', '#companyPhone', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        var reg = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$|(^(13[0-9]|15[0-9]|18[5|8|9])\d{8}$)/;
        if (!reg.test(companyPhone)) {
            layer.tips('电话号码格式错误，可填固定电话或手机', '#companyPhone', {
                tips : 3
            });
            return false;
        } else {
            return true;
        }
    }
}

// 验证公司紧急联系人手机
function checkUrgentContactorPhone() {
    var urgentContactorPhone = $("#urgentContactorPhone").val();
    if (urgentContactorPhone == $("#urgentContactorPhone").attr("placeholder")) {
        urgentContactorPhone = "";
    }
    if (urgentContactorPhone == null || urgentContactorPhone == "") {
        layer.tips('请填写公司紧急联系人手机!', '#urgentContactorPhone', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        var reg = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$|(^(13[0-9]|15[0-9]|18[5|8|9])\d{8}$)/;
        if (!reg.test(urgentContactorPhone)) {
            layer.tips('电话号码格式错误，可填固定电话或手机', '#urgentContactorPhone', {
                tips : 3
            });
            return false;
        } else {
            return true;
        }
    }
}

//验证经营范围
function checkBusinessScope() {
    var businessScope = $("#businessScope").val();
    if (businessScope == $("#businessScope").attr(
            "placeholder")) {
    	businessScope = "";
    }
    if (businessScope == null || businessScope == "") {
        layer.tips('请填写经营范围!', '#businessScope', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

//验证公司详细地址
function checkCompanyAddress() {
    var companyAddress = $("#companyAddress").val();
    if (companyAddress == $("#companyAddress").attr(
            "placeholder")) {
    	companyAddress = "";
    }
    if (companyAddress == null || companyAddress == "") {
        layer.tips('请填写公司详细地址!', '#companyAddress', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

//验证紧急联系人
function checkUrgentContactor() {
    var urgentContactor = $("#urgentContactor").val();
    if (urgentContactor == $("#urgentContactor").attr(
            "placeholder")) {
    	urgentContactor = "";
    }
    if (urgentContactor == null || urgentContactor == "") {
        layer.tips('请填紧急联系人!', '#urgentContactor', {
            tips : 3,
            time : 1000
        });
        return false;
    } else {
        return true;
    }
}

// 保存商户入驻信息
var index = parent.layer.getFrameIndex(window.name); // 先得到当前iframe层的索引
function saveLisence() {
    var contactor = $("#contactor").val();
    var contactorPhone = $("#contactorPhone").val();
    var provinceId = $("#provinceId").val();
    var cityId = $("#cityId").val();
    var areaId = $("#areaId").val();
    var cellId = $("#cellId").val();
    var descrip = $("#descrip").val();
    var shopCategoryId = $("#shopCategoryId").val();

    var shopName = $("#shopName").val();
    var companyName = $("#companyName").val();
    var businessLicense = $("#businessLicense").val();
    var legalName = $("#legalName").val();
    var legalIdcard = $("#legalIdcard").val();

    var legalIdcardPhoto = $('#imageLogo').val();

    var businessLicenseProvinceid = $("#province1").val();
    var businessLicenseCityid = $("#city1").val();
    var businessLicenseAreaid = $("#district1").val();
    var businessLicenseAddress = $("#businessLicenseAddress").val();
    var registerDate = $("#registerDate").val();

    var beginDate = $("#beginDate").val();
    var endDate = $("#endDate").val();
    var check = document.getElementById('check').checked; // 这里返回 true 或 false
    if (check) {
        endDate = "2060-01-01";
    }
    var start = new Date(beginDate.replace("-", "/").replace("-", "/"));
    var end = new Date(endDate.replace("-", "/").replace("-", "/"));

    if (endDate != "" && beginDate == "") {
        layer.msg("请选择开始时间", {
            icon : 3,
            time : 1000
        // 2秒关闭（如果不配置，默认是3秒）
        });
    } else if (end < start) {
        layer.msg("结束时间应大于起始时间", {
            icon : 3,
            time : 1000
        // 2秒关闭（如果不配置，默认是3秒）
        });
    }

    var registerMoney = $("#registerMoney").val();
    var businessScope = $("#businessScope").val();

    var businessLicensePhoto = $('#imageLogo1').val();

    var companyProvinceid = $("#province2").val();
    var companyCityid = $("#city2").val();
    var companyAreaid = $("#district2").val();

    var companyAddress = $("#companyAddress").val();
    var companyPhone = $("#companyPhone").val();
    var urgentContactor = $("#urgentContactor").val();
    var urgentContactorPhone = $("#urgentContactorPhone").val();
    
    if (checkCompanyName() && checkBusinessLicense() && checkLegalName()
            && checkLegalIdcard() && checkImageLogo() && checkProvinceName1()
            && checkCityName1() && checkDistrict1() && checkProvinceName1()
            && checkCityName1() && checkDistrict1()
            && checkBusinessLicenseAddress() && checkRegisterDate()
            && checkBeginDate() && checkEndDate() && checkCompanyPhone()
            && checkUrgentContactorPhone() && checkMoney() && checkBusinessScope() && checkCompanyAddress() && checkUrgentContactor()) {
    	
    	var index1 = layer.load(1);
    	
    	$.ajax({
            type : "POST",
            url : ctx + "/saveLisence",
            cache : false,
            dataType : 'json',
            data : {
                contactor : contactor,
                contactorPhone : contactorPhone,
                provinceId : provinceId,
                cityId : cityId,
                areaId : areaId,
                cellId : cellId,
                descrip : descrip,
                shopCategoryId : shopCategoryId,

                shopName : shopName,
                companyName : companyName,
                businessLicense : businessLicense,
                legalName : legalName,
                legalIdcard : legalIdcard,
                legalIdcardPhoto : legalIdcardPhoto,
                businessLicenseProvinceid : businessLicenseProvinceid,
                businessLicenseCityid : businessLicenseCityid,
                businessLicenseAreaid : businessLicenseAreaid,
                businessLicenseAddress : businessLicenseAddress,
                registerDate : registerDate,
                beginDate : beginDate,
                endDate : endDate,
                registerMoney : registerMoney,
                businessScope : businessScope,
                businessLicensePhoto : businessLicensePhoto,
                companyProvinceid : companyProvinceid,
                companyCityid : companyCityid,
                companyAreaid : companyAreaid,

                companyAddress : companyAddress,
                companyPhone : companyPhone,
                urgentContactor : urgentContactor,
                urgentContactorPhone : urgentContactorPhone
            },
            success : function(result) {
                if (result.success) {
                    layer.msg("谢谢您的申请，我们的工作人员会尽快审核然后与您联系！", {
                        icon : 1,
                        time : 2000
                    // 2秒关闭（如果不配置，默认是3秒）
                    }, function() {
                        var userAccount = $("#userAccount").val();
                        if (userAccount == null) {
                        	layer.close(index1);
                            window.location.href = ctx;
                        } else {
                        	layer.close(index1);
                            window.location.href = ctx + "/main?item=1";
                        }
                        // parent.window.location.href= ctx + "/index?item=1";
                    });
                } else {
                    layer.msg("操作失败", {
                        icon : 2,
                        time : 1000
                    });
                    layer.close(index1);
                }
            }
        });
    }
}

function back() {
    var userAccount = $("#userAccount").val();
    if (userAccount == null) {
        window.location.href = ctx;
    } else {
        window.location.href = ctx + "/main?item=1";
    }
}